import { Component, OnInit, OnDestroy } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { ResWalletBalance, UserWithdrawalAddressMobileList } from '../../../../model';
import { TransferService } from '../../service/transfer.service';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { StorageService } from 'src/app/core/sotrage/storage.service';
import { ApiService, urlService } from 'src/app/core/api';

@Component({
  selector: 'app-transfer-form',
  templateUrl: './transfer-form.component.html',
  styleUrls: ['./transfer-form.component.scss']
})
export class TransferFormComponent implements OnInit, OnDestroy {

  _amount: number;
  internal: string = 'N';//收款地址是否是内部轉賬地址 Y 是 ： N 否
  validateForm: FormGroup;
  isVisible = false;
  isConfirmLoading = false;
  userWithdrawalAddressMobiles: UserWithdrawalAddressMobileList[];
  autocompleteUserWithdrawalAddressMobilesDatasource: UserWithdrawalAddressMobileList[];
  transferForm: FormGroup;
  resWalletBalance: ResWalletBalance;
  poundage: number;
  innerpoundage: number;
  subscriptions: Subscription[] = [];
  coin: any = this.storage.get('coin')

  get address(): AbstractControl {
    return this.transferForm.get('address');
  }

  get amount(): AbstractControl {
    return this.transferForm.get('amount');
  }

  get fundPwd(): AbstractControl {
    return this.transferForm.get('fundPwd');
  }


  constructor(
    private transferService: TransferService,
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private storage: StorageService,
    private api: ApiService,
  ) {
    this.transferForm = this.fb.group({
      address: [null, [Validators.required]],
      amount: [null, [Validators.required]],
      fundPwd: [null, [Validators.required]]
    });
    this.validateForm = this.fb.group({
      address: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9_]{18,48}$')]],
      tag: ['', []],
    });
    this.subscriptions.push(this.transferForm.get('address').valueChanges.subscribe(res => {
      this.autocompleteUserWithdrawalAddressMobilesDatasource =
        this.userWithdrawalAddressMobiles.filter(value => value.address.includes(res) || value.tag.includes(res));
    }));
  }

  onSubmit() {
    // tslint:disable-next-line:forin
    for (const i in this.transferForm.controls) {
      this.transferForm.controls[i].markAsDirty();
      this.transferForm.controls[i].updateValueAndValidity();
    }
    const value = this.transferForm.value as {
      amount: number,
      fundPwd: string,
      address: string
    };
    const index = this.userWithdrawalAddressMobiles.findIndex(v => v.tag === value.address);
    if (index > -1) {
      value.address = this.userWithdrawalAddressMobiles[index].address;
    }
    this.transferService.doTransfer({
      address: value.address,
      amount: value.amount + this.poundage,
      coinName: this.coin.coinName,
      fundPwd: value.fundPwd,
    }).subscribe(res => {
      if (res.status === 0) {
        this.router.navigateByUrl('member/transfer/success');
        this.router.navigate(['member/transfer/success'], {
          queryParams: {
            transactionId: res.data.transactionId
          }
        });
      } else {
        this.transferService.error(res);
      }
    }, error => this.transferService.error(error));
  }

  onChange(f) {
    f ? this.getIsInGroup(f) : null;
  }


  addBank() {
    this.validateForm.reset();
    this.isVisible = true;
  }

  async handleOk(fromData) {
    this.isConfirmLoading = true;
    fromData.coinName = this.coin['coinName'];
    let data = await await this._getAJX('用户创建转账地址', fromData);
    this.api.getData(data, { bool: true, msg: '创建成功！' }) ? this._successOk() : this.isVisible = this.isConfirmLoading = false;
  };
  async getIsInGroup(f) {
    let fromData = {
      coinName: this.coin['coinName'],
      address: f
    };
    this.userWithdrawalAddressMobiles.map((item) => {
      if (item.tag == f) {
        fromData.address = item.address
      }
    });
    let data = await await this._getAJX('判断地址是否为 平台内/外部', fromData);
    this.api.getData(data, false) ? this.internal = data.data.internal : null;
    (this.internal == 'Y') ? this.setValid(this.resWalletBalance.availableBalance - this.poundage) : this.setValid(this.resWalletBalance.availableBalance - this.innerpoundage)
  };

  handleCancel() {
    this.validateForm.reset();
    this.isVisible = false;
  }

  addAll() {
    if (this.internal == 'Y') {
      this._amount = this.resWalletBalance.availableBalance - this.poundage;
    } else {
      this._amount = this.resWalletBalance.availableBalance - this.innerpoundage;
    }
  }

  private _getAJX(url: string, data: any): any {//接口交換
    let success = this.api.post(urlService('dev', url), data).toPromise();
    return success;
  };

  private _successOk(): void {
    this.isVisible = this.isConfirmLoading = false;
    this.transferService.listAllTransfer().subscribe(res => {
      this.userWithdrawalAddressMobiles = res || [];
      this.autocompleteUserWithdrawalAddressMobilesDatasource = this.userWithdrawalAddressMobiles;
    });
  };

  ngOnInit() {
    this.transferService.changeGoBackUrl('/member/center');
    this.transferService.listAllTransfer().subscribe(res => {
      this.userWithdrawalAddressMobiles = res || [];
      this.autocompleteUserWithdrawalAddressMobilesDatasource = this.userWithdrawalAddressMobiles;
    });
    this.transferService.getWalletInfo().subscribe(res => {
      if (res.status === 0) {
        this.resWalletBalance = res.data;
        console.log(this.internal)
        if (this.internal == 'Y') {
          this.setValid(this.resWalletBalance.availableBalance - this.poundage)
        } else {
          this.setValid(this.resWalletBalance.availableBalance - this.innerpoundage)
        }
        this.poundage = res.data.coin.withdrawalFeeAmount;
        this.innerpoundage = res.data.coin.withdrawalInnerFeeAmount;
      }
    });
  }

  setValid(availableBalance): void {
    this.amount.setValidators(
      [
        Validators.required,
        Validators.max(availableBalance),
        Validators.min(this.resWalletBalance.coin.withdrawalInnerFeeAmount),
      ]);
  }

  ngOnDestroy(): void {
    if (this.subscriptions && this.subscriptions.length > 0) {
      this.subscriptions.forEach(subscription => {
        subscription.unsubscribe();
      });
      this.subscriptions = [];
    }
  }


};

